package com.topvision.controller.app;


import com.topvision.constants.AppConstants;
import com.topvision.constants.TopVisionWebConstants;
import com.topvision.model.glass.SysFileUploadStatus;
import com.topvision.model.glass.Sysupload;
import com.topvision.service.api.glass.AppLauncherService;
import com.topvision.service.api.glass.AppSysUploadService;
import com.topvision.service.glass.SysuploadService;
import com.topvision.util.R;
import com.topvision.util.ftp.SFTPUpload;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@Api(value = "智能眼镜接口类", description = "包含系统设置、录像机文件上传等")
@RequestMapping("app/launcher")
public class AppLauncherController {

    @Autowired
    AppLauncherService appLauncherService;
    @Autowired
    AppSysUploadService appSysUploadService;

    @RequestMapping(value = "/video/ckeckFileServlet", method = RequestMethod.POST)
    @ApiOperation(value = "录像机相关功能", produces = MediaType.APPLICATION_JSON_VALUE, notes = "查看本地文件是否已上传", response = R.class)
    public R ckeckFileServlet(@RequestParam String guid, @RequestParam String fileName) {
        System.out.println(fileName);
        SysFileUploadStatus file = appLauncherService.get(guid, fileName);
        int schunk = 1;
        try {
            if (file != null) {
                schunk = file.getChunk();
                deleteFile(AppConstants.SYSUPLOAD_PATH + schunk + "_" + fileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
        return R.success(schunk);
    }

    @RequestMapping(value = "/video/uploaderWithContinuinglyTransferring", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @ApiOperation(value = "文件续传", response = R.class)
    public R uploaderWithContinuinglyTransferring(HttpServletRequest request, @RequestParam("file") MultipartFile[] files, String guid, Integer chunk, Integer chunks) {
        String server_path = AppConstants.SYSUPLOAD_PATH + "video/" + guid;
        for (int k = 0; k < files.length; k++) {
            MultipartFile file = files[k];
            // 保存文件
            String fileName = file.getOriginalFilename();
            if (chunk != null) {
                //分块文件名称
                String chuckName = guid + "_" + chunk + "_" + fileName;
                SysFileUploadStatus sysFileUploadStatus = appLauncherService.get(guid, chuckName);
                //数据已存在
                if (sysFileUploadStatus != null && sysFileUploadStatus.getChunk() == chunks) {
                    return R.error("该分块已经上传");
                }
                try {
                    //SFTP 上传
                    SFTPUpload.upload(file.getInputStream(), chuckName,
                            server_path);
                    //保存相关记录
                    SysFileUploadStatus dbEntity = appLauncherService.get(guid, fileName);
                    if (dbEntity != null) {
                        dbEntity.setChunk(chunk);
                        appLauncherService.updateChunk(dbEntity);
                    } else {
                        SysFileUploadStatus saveSysFileUploadEntity = new SysFileUploadStatus(guid, fileName, chunk, chunks);
                        appLauncherService.add(saveSysFileUploadEntity);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //文件合并功能
                if (chunk != null && chunk.intValue() == chunks.intValue()) {
                    try {
                        File outFile = new File(server_path, fileName);
                        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outFile));
                        // 遍历文件合并
                        for (int i = 1; i <= chunks; i++) {
                            File tempFile = new File(server_path, guid + "_" + i + "_" + fileName);
                            byte[] bytes = FileUtils.readFileToByteArray(tempFile);
                            outputStream.write(bytes);
                            tempFile.delete();
                            outputStream.flush();
                        }
                        //网络访问权限
                        String netUrl = TopVisionWebConstants.SERVER_DIR_VIDEO_PATH + guid + "/" + outFile.getName();
                        Sysupload sysupload = appSysUploadService.get(netUrl);
                        if (sysupload == null) {
                            sysupload = new Sysupload();
                            // 后缀
                            String fileExt = fileName.substring(fileName.lastIndexOf("."));
                            sysupload.setFilefullpath(netUrl);
                            // 客户端请求的ip地址
                            String clientName = request.getRemoteAddr();
                            // 设置服务器ip
                            String serverName = request.getServletPath();
                            sysupload.setClientname(clientName);
                            sysupload.setServername(serverName);
                            sysupload.setFileext(fileExt);
                            sysupload.setModuleid(AppConstants.STR_VIDEO);
                            sysupload.setGuid(guid);
                            sysupload.setFilesize(Integer.parseInt((file.getSize() + "")));
                            sysupload.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
                            sysupload.setIsdeleted(TopVisionWebConstants.DELETED_FALSE);
                            appSysUploadService.save(sysupload);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return R.success("完成");
                }
            }
        }
        return R.success();
    }


    public boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
}
